import { shallowRef, onUnmounted, Ref, watchEffect } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
export function useMap(
  mapContainerRef: Ref<HTMLDivElement | undefined>,
  location: [number, number]
) {
  const map = shallowRef<AMap.Map | null>(null)
  const auto = shallowRef<any>(null)
  const geocoder = shallowRef<any>(null)
  const placeSearch = shallowRef<any>(null)
  const mousetool = shallowRef<any>(null)
  const initAmap = async () => {
    // 使用 async 函数来处理异步加载
    window._AMapSecurityConfig = {
      securityJsCode: '9fdee0f531a82441f583307b2242b6bf'
    }

    try {
      const AMap = await AMapLoader.load({
        key: 'b38a6630d229ce13fd91236baace6671',
        version: '2.0',
        plugins: [
          'AMap.ToolBar',
          'AMap.Scale',
          'AMap.AutoComplete',
          'AMap.PlaceSearch',
          'AMap.Geocoder',
          'AMap.MoveAnimation',
          'AMap.MouseTool'
        ]
      })

      map.value = new AMap.Map(mapContainerRef.value, {
        viewMode: '2D',
        zoom: 14,
        center: location,
        mapStyle: 'amap://styles/normal',
        showIndoorMap: false
      })

      // 初始化其他插件
      const ToolBar = new AMap.ToolBar({
        position: 'RB',
        liteStyle: true
      })
      mousetool.value = new AMap.MouseTool(map.value)
      const scale = new AMap.Scale()
      auto.value = new AMap.AutoComplete({
        datatype: 'all'
      })
      geocoder.value = new AMap.Geocoder({
        extensions: 'base'
      })
      placeSearch.value = new AMap.PlaceSearch({
        map: map.value,
        autoFitView: true
      })
      map.value?.addControl(scale)
      map.value?.addControl(ToolBar)
      return true // 表示初始化成功
    } catch (e) {
      console.log(e)
      return false // 表示初始化失败
    }
  }
  const getAddress = (longitude: number, latitude: number) => {
    return new Promise((resolve, reject) => {
      // 确保geocoder已经定义
      if (!geocoder.value) {
        reject(new Error('Geocoder 未初始化'))
        return
      }

      geocoder.value.getAddress(
        new AMap.LngLat(longitude, latitude),
        (status: string, result: any) => {
          if (status === 'complete' && result.regeocode) {
            resolve(result.regeocode.formattedAddress)
          } else {
            reject(new Error(`获取地址失败: ${result.info}`))
          }
        }
      )
    })
  }
  watchEffect(() => {
    map.value?.setCenter(location)
  })
  onUnmounted(() => {
    map.value?.destroy()
  })

  return { map, auto, geocoder, placeSearch, initAmap, getAddress, mousetool }
}
